#include "person.pb.h"
#include <fstream>
#include <iostream>
#include <stdint.h>
#include <vector>
using namespace std;

// 写入文件
void WriteToFile(const std::string& filename, const example::Person& person) {
  std::fstream output(filename, std::ios::out | std::ios::trunc | std::ios::binary);
  if (!person.SerializeToOstream(&output)) {
    std::cerr << "Failed to write person." << std::endl;
  }
}

// 从文件读取
void ReadFromFile(const std::string& filename, example::Person& person) {
  std::fstream input(filename, std::ios::in | std::ios::binary);
  if (!person.ParseFromIstream(&input)) {
    std::cerr << "Failed to parse person." << std::endl;
  }
}

// 打印反序列化后的数据
void PrintPerson(const example::Person& person) {
  std::cout << "Name: " << person.name() << std::endl;
  std::cout << "ID: " << person.id() << std::endl;
  std::cout << "Is Active: " << person.is_active() << std::endl;
  // 打印反序列化后的数据
  for (int i = 0; i < person.email_size(); ++i) {
    std::cout << "Email " << i + 1 << ": " << person.email(i) << std::endl;
  }
}

int main() {
  // 创建并填充一个Person对象
  example::Person person;
  person.set_name("Alice");
  person.set_id(123);
  person.set_is_active(true);
  person.add_email("alice@example.com");
  person.add_email("alice.personal@gmail.com");

  // 1.序列化到 字节
  uint8_t buf[256] = { 0 };
  bool ret = person.SerializeToArray(buf, sizeof(buf));

  // 2.反序列化从 字节
  example::Person new_person;
  ret = new_person.ParseFromArray(buf, sizeof(buf));

  cout << "result ret: " << ret << endl;
  PrintPerson(new_person);

  // 3.读写probuf测试
  WriteToFile("person.bin", person);  // 写入文件
  ReadFromFile("person.bin", new_person); // 从文件读取
  PrintPerson(new_person);            // 打印反序列化后的数据

  return 0;
}